//
//  HZNetTools.swift
//  网络工具类
//
//  Created by 黑眼圈 on 16/4/18.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import AFNetworking


//枚举
enum HZRequestMethod: String{
    
    case Post = "post"
    case Get = "get"
    
}


class HZNetTools: AFHTTPSessionManager {
    
    
    //单例对象
    static let sharedTools:HZNetTools = {
        
        let tool = HZNetTools()
        
        //添加一条解析的类型
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tool
    }()
    
    
    
    func uploadImg(urlString:String,parameter:AnyObject?,imgDict:[String:AnyObject],finishedClosure:((thing:AnyObject?,error:NSError?)->())){
        
        
        HZNetTools.sharedTools.POST(urlString, parameters: parameter, constructingBodyWithBlock: { (formData) -> Void in
            
            //取出图片
            let img = imgDict["pic"] as! UIImage
            
            //装换成二进制类型
            let data = UIImagePNGRepresentation(img)
            
            
            formData.appendPartWithFileData(data!, name: "pic", fileName: "123", mimeType: "application/octet-stream")
            
            }, success: { (_, respont) -> Void in
                
                 finishedClosure(thing: respont!,error: nil)
                
            }) { (_, error) -> Void in
                
                finishedClosure(thing: nil,error: error)
        }
        

    }
    
    
    
    //封装网络请求
    /// - parameter requestMethod:     请求方式
    /// - parameter urlString:         请求地址
    /// - parameter parameter:         请求参数
    /// - parameter finishedClosure:   请求完成之后的回调
    func deliveryThing(requestMethod requestMethod:HZRequestMethod,urlString:String,parameter:AnyObject?,finishedClosure:(thing:AnyObject?,error:NSError?)->()){
        
        
        //成功的闭包回调
        let success = { (dataTask :NSURLSessionDataTask, responstObject:AnyObject?)->() in
            
            finishedClosure(thing: responstObject!,error: nil)
        }
        
        //错误的闭包回调
        let fail = { (dataTask:NSURLSessionDataTask?, error:NSError) -> () in
            
            finishedClosure(thing: nil,error: error)
        }
        
        if requestMethod == .Get {
           
            //get 请求
            self.GET(urlString, parameters: parameter, progress: nil, success: success, failure: fail)
        }else{
            
            
            //post请求
            self.POST(urlString, parameters: parameter, progress: nil, success: success, failure: fail)
            
        }

        
    }

}
